package com.core;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class LoginCheckFilter implements Filter {
	
	protected FilterConfig filterConfig = null;
	
	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		filterConfig = null;
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest httprequest = (HttpServletRequest) request;
		HttpSession session = httprequest.getSession();
		String isLogin = "";
//		PrintWriter toClientTextOutStream = new PrintWriter(response.getOutputStream());
		
		try { // �����session�����¼��isLogin���ԣ��������ɵ�¼���ֵĴ���д��
			isLogin = (String) session.getAttribute("isLogin");
			if ((isLogin != null) && isLogin.equals("true")) // ��֤�ɹ���������
			{
				chain.doFilter(request, response);
			} else // ��֤���ɹ������û���¼��
			{
				PrintWriter toClientTextOutStream = new PrintWriter(response.getOutputStream());
				toClientTextOutStream.print("<script language=\"JavaScript\">");
				toClientTextOutStream.print("alert(\"��δ��¼���¼��ʱ�������µ�½\");");
				String targetURL = "/OnlineExamPro/";
				toClientTextOutStream.print("window.top.location=\""
						+ targetURL + "\";");
				toClientTextOutStream.print("</script>");
				toClientTextOutStream.flush();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		// TODO Auto-generated method stub
		this.filterConfig = filterConfig;
		System.out.println("***LoginCheckFilter init***");
	}

}
